package com.sxs.app.service;

import com.sxs.app.dao.BackendUserDao;
import com.sxs.app.dao.DevUserDao;
import com.sxs.app.dto.LoginDto;
import com.sxs.app.entity.BackendUser;
import com.sxs.app.entity.DevUser;
import com.sxs.app.intercept.SeesionUtil;
import com.sxs.app.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class LoginService {
    @Autowired
    BackendUserDao backendUserDao;
    @Autowired
    DevUserDao devUserDao;


    public LoginUserVo login(LoginDto loginDto) {
        LoginUserVo vo = new LoginUserVo();

        //如果等于1，就是管理员
        if (loginDto.getUserType() == 1) {
            BackendUser backendUser = new BackendUser();
            backendUser.setUsercode(loginDto.getAccount());
            backendUser.setUserpassword(loginDto.getPassword());
            List<BackendUser> list = backendUserDao.queryAllBy(backendUser);
            if (list == null || list.size() == 0) {
                throw new RuntimeException("账号密码错误");
            }
            vo.setType((long) 1);
            vo.setAccount(list.get(0).getUsercode());

            StringBuffer token = new StringBuffer();
            //replace 替换 将 “-” 替换成 “ ”
            String uuid = UUID.randomUUID().toString().replace("-", "");
            token.append(uuid + "-");
            token.append(loginDto.getAccount() + "-");
            token.append(System.currentTimeMillis() + "-");
            token.append(1);
            vo.setToken(token.toString());
            //存起
            SeesionUtil.put(token.toString(), list.get(0));
            return vo;
        } else if (loginDto.getUserType() == 2) {
            DevUser devUser = new DevUser();
            devUser.setDevcode(loginDto.getAccount());
            devUser.setDevpassword(loginDto.getPassword());
            List<DevUser> list = devUserDao.queryAllBy(devUser);
            if (list == null || list.size() == 0) {
                throw new RuntimeException("账号密码错误");
            }
            vo.setType((long) 2);
            vo.setAccount(loginDto.getAccount());

            StringBuffer token = new StringBuffer();

            String uuuid = UUID.randomUUID().toString().replace("-", "");
            token.append(uuuid + "-");
            token.append(loginDto.getAccount() + "-");
            token.append(System.currentTimeMillis() + "-");
            token.append(2);

            vo.setToken(token.toString());
            SeesionUtil.put(token.toString(), list.get(0));
            return vo;
        }else {
            throw new RuntimeException("用户类型错误");
        }
    }
}

